import define from './define.js'
const host = define.baseURL;
const defaultOpt = {load: true}
function request(config) {
	config.options = Object.assign(defaultOpt, config.options ? config.options : {})
	const token = uni.getStorageSync('token')

	let header = {
		"Content-Type": "application/json;charset=UTF-8",
		"appid": define.wxAppid,
		identification: define.identification,
		...config.header
	}
	if (token) {
		header['X-Access-Token'] = token
	}
	let url = config.url.indexOf('http') > -1 ? config.url : host + config.url
	if (config.options.load) {
		
		uni.showLoading({
			title: config.options.loadText || '正在加载'
		})
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: config.data || null,
			method: config.method || 'GET',
			header: header,
			timeout: define.timeout,
			success: async (res) => {
				uni.hideLoading()
				if (res.statusCode == 200) {
					if (res.data.success == true) {
						resolve(res.data)
					} else {
						if (res.data.code == 200) {
							return resolve(res.data.data)
						} else if (res.data.code == 400) {
							// getApp().$vm.exit();
						} else if (res.data.code == 401) {
							getApp().$vm.exit();
							if(define.identification=='user'){
								uni.switchTab({
									url:"/pages/userPage/home/index"
								})
							}else{
								uni.redirectTo({
									url:"/pages/login/login"
								})
							}
						} else {

							ajaxError(res.data)
							reject(res.data.message)
						}

					}

				} else {
					ajaxError(res.data)
					reject(res.data.message)
				}
			},
			fail: err => {
				uni.showToast({
					title: '连接服务器失败',
					icon: 'none',
				})
				uni.hideLoading({
					"noConflict": true
				})

				reject(err)
			}
		})
	})
}

function fungoPreviousPage() {
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let curRoute = routes[routes.length - 1].route //获取当前页面路由
	let curParam = routes[routes.length - 1].options; //获取路由参数
	// 拼接参数
	let param = ''
	for (let key in curParam) {
		if (!param) {
			param += key + '=' + curParam[key]
		} else {
			param += '&' + key + '=' + curParam[key]
		}
	}
	uni.setStorageSync('pageUrl', param ? `/${curRoute}?${param}` : `/${curRoute}`)
}

function ajaxError(data) {
	if (data.code === 401) {
		uni.clearStorageSync()
		fungoPreviousPage()
		uni.showToast({
			title: "您还未登录，请先登录!",
			icon: 'none',
			complete() {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}, 1000)
			}
		})

	} else {
		if(data.message!="对方未注册账户！"){
			uni.showToast({
				title: data.message || '请求出错，请重试',
				icon: 'none'
			})
			
		}
		
	}

}
export default request